package cn.hu.basic.exception;

import cn.hu.basic.util.AjaxResult;
import cn.hu.basic.commonenum.ErrorCode;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.io.IOException;

/**
 * 全局异常处理
 */
@RestControllerAdvice//对所有加了RequestMapping的类进行增强
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)//捕获指定的异常
    public AjaxResult customExceptionHandler(CustomException e){
        e.printStackTrace();
        //通过code获取枚举对象
        ErrorCode error = ErrorCode.getByCode(e.getMessage());
        return AjaxResult
                .getInstance()
                .setCode(error.getCode())
                .setSuccess(false)
                .setMessage(error.getMessage());
    }

    /**
     * springvalidation对象校验参数异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)//捕获指定的异常
    public AjaxResult methodArgumentExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        return AjaxResult
                .getInstance()
                .setCode("400")
                .setSuccess(false)
                .setMessage("参数异常");
    }

    /**
     * springvalidation单个参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)//捕获指定的异常
    public AjaxResult constraintViolationExceptionHandler(ConstraintViolationException e){
        e.printStackTrace();
        return AjaxResult
                .getInstance()
                .setCode("400")
                .setSuccess(false)
                .setMessage("参数异常");
    }

    /**
     * 捕获非业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)//使用异常类的祖先类可以捕获其子类的异常
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult
                .getInstance()
                .setCode(ErrorCode.SYSTEM_ERROR.getCode())
                .setSuccess(false)
                .setMessage(ErrorCode.SYSTEM_ERROR.getMessage());
    }

}
